<template>
  <div class="top-tab" style="background-color: white">
    <a-tabs v-model:active-key="curPage" @change="tabChange" size="mini">
      <a-tab-pane title="链条" key="1"></a-tab-pane>
      <a-tab-pane title="石头" key="2"></a-tab-pane>
    </a-tabs>
  </div>
  <div class="shop-list-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal">
        <template #filterItemRight>
          <a-button type="text" class="filter-item ml10" @click="searchForPropertyVisible = true">
            <template #icon>
              <span>属性筛选</span>
              <span class="red-dot" v-show="isShowDot"></span>
            </template>
          </a-button>
        </template>
      </FilterTable>
    </div>
    <div class="table-gl-con mt10">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerLeft>
          <a-space>
            <a-button class="gray-outline" @click="show('add')">新增</a-button>
            <a-button class="gray-outline" @click="stop">作废</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table :data="tableData" size="mini" row-key="id" v-model:selected-keys="ids" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" class="table-single-line" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column type="index" title="序号" :width="40" #cell="{ rowIndex }">{{ rowIndex + 1 }}</a-table-column>
              <a-table-column title="图片" prop="name" :width="60" #cell="{ record }">
                <ImgPopover :src="imgUrl(record)">
                  <template #con>
                    <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(record)" />
                  </template>
                </ImgPopover>
              </a-table-column>
              <a-table-column title="SKU" prop="name" :width="60" #cell="{ record }">
                <textLimit @click="toDetail(record)" class="highlight cursor" position="top" :rows="1" :val="record.sku"></textLimit>
              </a-table-column>
              <a-table-column title="名称" prop="name" :width="100" #cell="{ record }">
                <textLimit position="top" :rows="1" :val="record.skuName"></textLimit>
              </a-table-column>

              <a-table-column v-for="(item, index) of currentTabProertyList" :key="index" :title="item.name" prop="name" :width="80" #cell="{ record }">
                <div v-if="item.name != '备注'"> {{ getPropVal(item, record) }}</div>
                <div v-if="item.name == '备注'">
                  <textLimit position="top" :rows="1" :val="getPropVal(item, record)"></textLimit>
                </div>
              </a-table-column>

              <a-table-column title="状态" prop="name" :width="60" #cell="{ record }">
                <div v-if="record.status == 'ACTIVE'">可用</div>
                <div v-if="record.status == 'NOT_ACTIVE'">已作废</div>
              </a-table-column>
              <a-table-column title="添加时间" prop="name" :width="140" #cell="{ record }">
                {{ $setTime(record.gmtCreate) }}
              </a-table-column>
              <a-table-column title="更新时间" prop="name" :width="140" #cell="{ record }">
                {{ $setTime(record.gmtWrite) }}
              </a-table-column>
              <a-table-column title="操作" #cell="{ record }" :width="40">
                <a-button type="text" v-if="record.status == 'ACTIVE'" @click="show('edit', record)">编辑</a-button>
                <a-button type="text" v-if="record.status == 'NOT_ACTIVE'" @click="start(record)">启用</a-button>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <detail v-if="detailVisible" v-model="detailVisible" :type="type" :categoryId="curPage == '1' ? chainCatId : stoneCatId" :curTabTitle="curPage == '1' ? '链条' : '石头'" :info="info" :propList="currentTabProertyList" @save="getList" />
  <itemDetail v-if="itemDetailVisible" v-model="itemDetailVisible" :curTabTitle="curPage == '1' ? '链条' : '石头'" :info="info" />
  <searchForProperty v-if="searchForPropertyVisible" v-model="searchForPropertyVisible" :formList="queryPropList" :propsList="currentTabProertyList" @search="searchForPro" />
</template>

<script lang="ts" setup>
  import { computed, ref, onMounted } from 'vue'
  import { getOrganizesUser } from '@/api/system'
  import { getPropertyTemplateList, pageFitting, batchUpdateStateByIdList } from '@/api/product'
  import { Message, Modal } from '@arco-design/web-vue'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import detail from './detail.vue'
  import itemDetail from './itemDetail.vue'
  import searchForProperty from './searchForProperty.vue'
  const chainCatId = import.meta.env.VITE_CHAIN_CATEGORY_ID
  const stoneCatId = import.meta.env.VITE_STONE_CATEGORY_ID
  const isShowDot = computed(() => {
    let flag = false
    queryPropList.value.forEach((e: any) => {
      e.valueList[0] || e.startNum || e.endNum ? (flag = true) : ''
    })
    return flag
  })
  const filterItem: any = ref([
    {
      type: 'input_search',
      key: 'skuNameList',
      keyWidth: '90',
      value: ref(),
      placeholder: '名称',
      label: '名称',
      width: 200,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skuList',
      keyItems: [{ label: 'SKU', value: 'skuList' }],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: 'SKU',
      width: 160,
      isMultiple: true,
    },
    {
      key: 'status',
      label: '状态',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        { label: '可用', value: 'ACTIVE' },
        { label: '已作废', value: 'NOT_ACTIVE' },
      ],
    },
  ])
  const queryPropList = ref([])
  const tableData = ref([])
  const loading = ref(false)
  const detailVisible = ref(false)
  const itemDetailVisible = ref(false)
  const searchForPropertyVisible = ref(false)
  const curPage = ref('1')
  const ids = ref([])
  const searchValue = ref({})
  const type = ref('add')
  const info = ref({})
  const chainProperty = ref<Array<any>>([])
  const stoneProperty = ref<Array<any>>([])
  const currentTabProertyList = ref<Array<any>>([])
  const pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })

  // 显示弹框
  const show = (showType: string, data?: any) => {
    type.value = showType
    info.value = data
    detailVisible.value = true
  }

  // 搜索
  const searchByVal = (info: any) => {
    searchValue.value = info
    getList()
  }
  // 分页
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const imgUrl = (data: any) => {
    const arr = data?.productPicList || []
    return arr[0]?.url || ''
  }

  const getPropVal = (item: any, data: any) => {
    const arr = data.propList || []
    const option = arr.find((val: any) => val.name == item.name)
    if (option?.valueStr) return option?.valueStr || ''
    if (option?.valueStrList) return option.valueStrList.join(',') || ''
  }

  const getList = async () => {
    const params: any = {
      ...searchValue.value,
      queryPropList: queryPropList.value,
      categoryId: curPage.value == '1' ? chainCatId : stoneCatId,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }

    if (params.skuNameList) {
      params.skuNameList = params.skuNameList.split(',')
    } else {
      delete params.skuNameList
    }

    if (params.skuList) {
      params.skuList = params.skuList.split(',')
    } else {
      delete params.skuList
    }

    loading.value = true
    const res: any = await pageFitting(params)
    loading.value = false
    if (res) {
      tableData.value = res?.data?.records || []
      pageNation.value.total = res?.data?.total || 0
    }
  }

  const tabChange = (val: string) => {
    curPage.value = val
    queryPropList.value = []
    pageNation.value.pageNum = 1
    curPage.value == '1' ? (currentTabProertyList.value = chainProperty.value) : (currentTabProertyList.value = stoneProperty.value)
    getList()
  }
  const getPropertyForCategory = (catId: string) => {
    const params = {
      scenes: 'prodcut',
      categoryId: catId,
    }
    return getPropertyTemplateList(params)
  }

  const stop = () => {
    if (!ids.value[0]) return Message.error('请选择数据')
    Modal.info({
      title: '提示',
      content: '请再次确认是否要作废',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const res: any = await batchUpdateStateByIdList({ idList: ids.value, status: 'NOT_ACTIVE' })
        if (res.code == 'SUCCESS') {
          Message.success('操作成功')
          getList()
          ids.value = []
        }
      },
    })
  }

  const start = (data: any) => {
    Modal.info({
      title: '提示',
      content: '请再次确认是启用',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const res: any = await batchUpdateStateByIdList({ idList: [data.id], status: 'ACTIVE' })
        if (res.code == 'SUCCESS') {
          Message.success('操作成功')
          getList()
          ids.value = []
        }
      },
    })
  }

  const toDetail = (data: any) => {
    info.value = data
    itemDetailVisible.value = true
  }

  const init = async () => {
    chainProperty.value = []
    stoneProperty.value = []
    const chainPropertyRes = await getPropertyForCategory(chainCatId)
    const arr = chainPropertyRes?.data?.records[0]?.itemList || []
    arr.forEach((e: any) => {
      const obj = {
        id: e.prop.id,
        propRequired: e.propRequired,
        code: e.prop.code,
        type: e.prop.type,
        name: e.prop?.name,
        nameEn: e.prop?.nameEn,
        propValueList: e.prop?.propValueList,
      }
      chainProperty.value.push(obj)
    })
    const stonePropertyRes = await getPropertyForCategory(stoneCatId)
    const arr1 = stonePropertyRes?.data?.records[0]?.itemList || []
    arr1.forEach((e: any) => {
      const obj = {
        id: e.prop.id,
        propRequired: e.propRequired,
        code: e.prop.code,
        type: e.prop.type,
        name: e.prop?.name,
        nameEn: e.prop?.nameEn,
        propValueList: e.prop?.propValueList,
      }
      stoneProperty.value.push(obj)
    })
    currentTabProertyList.value = chainProperty.value
    getList()
  }

  const searchForPro = (data: any) => {
    queryPropList.value = data
    getList()
  }

  onMounted(init)
</script>

<style lang="less" scoped>
  .shop-list-con {
    height: calc(100vh - @menuAndTabHeight);
  }

  .red-dot {
    position: absolute;
    width: 8px;
    height: 8px;
    background-color: red;
    border-radius: 50%;
    top: 0;
    right: -15px;
  }
</style>
